-- UISummonInfo
-- Created by chengb May/7/2015
-- 召唤兽信息界面

require "game/ui/module/summon/SummonDisplay"

local PROP_DESC_COUNT = 3;      -- 特性显示条数

UISummonInfo = class("UISummonInfo", function()
    return cc.Layer:create();
end);

function UISummonInfo.create(summon)
    return UISummonInfo.new(summon);
end

-- 构造函数
function UISummonInfo:ctor(summon)
    self:setName("UISummonInfo");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/monster/MonsterInfo.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.summon = summon;

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件回调
    self:registerEventCallback();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 注册事件回调
function UISummonInfo:registerEventCallback()
    -- 关注学习工程学手册
    EventMgr.register("UISummonInfo", event.LEARN_MANUAL_SUCCEED, function(para)
        -- 属性初始化
        self:initProp();

        -- 特性描述初始化
        self:initPropPanel();
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            EventMgr.removeAll("UISummonInfo");
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showTop();
            end
        elseif ev == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideTop();
            end
        end
    end);
end

-- 适配
function UISummonInfo:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册点击事件
function UISummonInfo:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISummonInfo");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    local btnBgBack = findChildByName(self.node, "bg/bgImg");
    local function onBgBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISummonInfo");
        end
    end
    btnBgBack:addTouchEventListener(onBgBackClick);

    local btnManual = findChildByName(self.node, "BT/btn_comment");
    local commentLabel = findChildByName(btnManual, "comment_label");
    commentLabel:setVisible(false);

    local function onManualClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 手册
            if EngineeringManualM.canOpen() then
                UIMgr.getCurrentScene():removeFormByName("UIEngineeringManual");
                local uiForm = UIEngineeringManual.create();
                UIMgr.getCurrentScene():addForm(uiForm);
                AudioM.playFx("ui_open2");
            else
                alert(getLocStr("engineering_manual_cannot_open"));
            end
        end
    end
    TextStyleM.setTextStyle(btnManual, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnManual:setTitleText(getLocStr("btn_text_machine"));
    btnManual:addTouchEventListener(onManualClick);

    local classId = self.summon:query("class_id");
    local rule = SummonM.query(classId, "rule");
    if rule and rule == "mechanic_spider"
        and EngineeringManualM.canOpen() then
        btnManual:setVisible(true);
    else
        btnManual:setVisible(false);
    end
end

-- 重绘
function UISummonInfo:redraw()
    local summonInfo = SummonM.query(self.summon.classId);

    -- 召唤兽名称
    local titleLabel = findChildByName(self.node, "CT/bg/bg/title_label");
    local name = summonInfo["name"];
    titleLabel:setString(name);
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 召唤兽模型
    self:createSummonDisplay();

    -- 属性初始化
    self:initProp();

    -- 特性描述初始化
    self:initPropPanel();
end

-- 属性初始化
function UISummonInfo:initProp()
    local classId = self.summon:query("class_id");
    local rule = SummonM.query(classId, "rule");
    local nodeNames = {"attack", "hp", "dodge", "accuracy"};
    local names;
    if rule and rule == "mechanic_spider" then
        -- 机械蜘蛛
        names = {"attack", "hp", "magic", "mp"};
        values = {
            self.summon:getAttack(),           -- 攻击
            self.summon:getHp(),               -- 生命
            self.summon:queryAttrib("magic"),  -- 魔力
            self.summon:queryAttrib("mp"),     -- 魔法
        };
    else
        names = {"attack", "hp", "dodge", "accuracy"};
        values = {
            self.summon:getAttack(),   -- 攻击
            self.summon:getHp(),       -- 生命
            self.summon:getDodge(),    -- 闪避
            self.summon:getAccuracy(), -- 命中
        };
    end

    local rightPart = findChildByName(self.node, "CT/bg/right_part");
    for i = 1, #nodeNames do
        local icon = findChildByName(rightPart, nodeNames[i] .. "_node/icon");
        icon:loadTexture(getSmallAttribIconPath(names[i]));

        local nameLabel = findChildByName(rightPart, nodeNames[i] .. "_node/name");
        TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
        nameLabel:setString(getLocStr(names[i]));

        local valueLabel = findChildByName(rightPart, nodeNames[i] .. "_node/value");
        TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
        valueLabel:setString(values[i]);
    end
end

-- 创建召唤兽模型
function UISummonInfo:createSummonDisplay()
    local classId = self.summon.classId;
    local monsterNode = findChildByName(self.node, "CT/model_node");
    if monsterNode.summonDisplay then
        -- 先移除旧模型
        monsterNode:removeChild(monsterNode.summonDisplay);
    end

    -- 创建模型
    local summonDisplay = SummonDisplay.create(classId);

    -- 设置缩放比例
    local scale = SummonM.query(classId, "model_scale");
    summonDisplay:setScale(scale);

    -- 设置偏移量
    local offsetX = SummonM.query(classId, "offset_x") or 0;
    local offsetY = SummonM.query(classId, "offset_y") or 0;
    summonDisplay:setPosition(tonumber(offsetX), tonumber(offsetY));

    monsterNode:addChild(summonDisplay);

    monsterNode:setScale(1.5);
end

-- 特性描述的panel初始化
function UISummonInfo:initPropPanel()
    --
    local scrollview = findChildByName(self.node, "CT/scrollview");
    scrollview:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/monster/MonsterInfoNode.csb");
    local widget = replaceNodeWithWidget(itemNode);

    -- 左边距
    local leftMargin = 1;

    -- 行间距
    local gap = 10;

    local startHeight = 10;

    -- 怪物描述
    local summonInfo = SummonM.query(self.summon.classId);
    local descInfo = SummonM.queryDesc(self.summon.classId);

    local combatStatus = self.summon.dbase:query("combat_status", {});

    for status, condition in pairs(combatStatus) do
        local title = CombatStatusM.getStatusName(self.summon, status);

        local desc = CombatStatusM.getStatusDesc(self.summon, status);
        local tipStr = "";

        if condition["end_round"] > 0 then
            local restRound = condition["end_round"] - CombatM.getRound();
            if restRound > 0 then
                tipStr = string.format(getLocStr("monster_buff_tip"), restRound);
            end
        end

        title = title .. tipStr;

        table.insert(descInfo, {name = title, desc = desc, bgColor = "red" });
    end

    local propBg;
    local propNameLabel;
    local propDescLabel;
    local totalHeight;
    local n = 1;
    local curHeight = 13;
    local ret = {};

    local count = math.max(PROP_DESC_COUNT, sizeof(descInfo));

    local itemName = "prop_";
    for i = 1, PROP_DESC_COUNT do

        repeat

            if descInfo[i] ~= nil then
                -- 找到描述了，设置描述内容

                table.insert(ret, curHeight)

                local child = widget:clone();
                child:setName(itemName .. n);
                child:setPosition(255, curHeight);

                propNameLabel = findChildByName(child, "prop_name");
                propDescLabel = findChildByName(child, "prop_desc");
                propBg        = findChildByName(child, "prop_bg");

                -- 设置文本风格
                TextStyleM.setTextStyle(propNameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
                TextStyleM.setTextStyle(propDescLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);

                if descInfo[i].name and descInfo[i].desc then
                    -- 普通的描述
                    propNameLabel:setString(getMonsterLocStr(descInfo[i].name));
                    propDescLabel:setString(extractString(getMonsterLocStr(descInfo[i].desc)));
                elseif summonInfo["dbase"]["aladdin"] and #PropM.fetchProps(ME.user, "summon_explode") > 0 then
                    -- 阿拉丁神灯，且可以自爆
                    propNameLabel:setString(getMonsterLocStr(descInfo[i].name2));
                    propDescLabel:setString(getMonsterLocStr(descInfo[i].desc2));
                else
                    break;
                end

                -- 文本可见
                propNameLabel:setVisible(true);
                propDescLabel:setVisible(true);

                if descInfo[i].bgColor ~= nil then
                    -- local colorPic = "point_" .. descInfo[i].bgColor;
                    local picRootPath = getTitleBgIconPath("point_red");
                    propBg:loadTexture(picRootPath);
                end

                -- 获得高的值
                local nameHeight = propNameLabel:getContentSize().height;
                local descHeight = propDescLabel:getContentSize().height;

                local propHeight = nameHeight + descHeight + 30;
                propBg:setContentSize(propBg:getContentSize().width, propHeight);

                curHeight = curHeight + propHeight + 10;

                n = n + 1;

                scrollview:addChild(child);
            end
        until true;
    end

    -- 重新调整位置
    --计算总高度
    local totalHeight = math.max(curHeight, scrollview:getInnerContainerSize().height);
    startHeight = totalHeight;

    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width, totalHeight));

    for j = 1, n - 1 do
        local child = findChildByName(scrollview, "prop_" .. j);
        local pos = ret[j];
        child:setPosition(cc.p(255, startHeight - pos));
    end
end
